package com.jeecg.p3.system.web.app;


import com.jeecg.p3.base.util.DateUtil;
import com.jeecg.p3.system.advisor.entity.StudyAdviser;
import com.jeecg.p3.system.advisor.service.StudyAdvService;
import com.jeecg.p3.system.base.BaseController;
import com.jeecg.p3.system.entity.JwSystemUser;
import com.jeecg.p3.system.order.entity.CourseOrder;
import com.jeecg.p3.system.order.service.CourseOrderService;
import com.jeecg.p3.system.poster.entity.PosterManager;
import com.jeecg.p3.system.poster.service.PosterManagerService;
import com.jeecg.p3.system.service.JwSystemUserService;
import com.jeecg.p3.system.vo.LoginUser;
import org.apache.velocity.VelocityContext;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.util.MD5Util;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.jeecgframework.p3.core.utils.common.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 手机端主页相关接口
 */
@Controller
@RequestMapping("/app/home")
public class HomeController extends BaseController {
    public Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private JwSystemUserService userService;
    @Autowired
    private StudyAdvService studyAdvService;
    @Autowired
    private PosterManagerService posterManagerService;
    @Autowired
    private CourseOrderService courseOrderService;

    /**
     * 跳转到工作台
     * @param request
     * @param response
     */
    @RequestMapping(value = "/toMain",method ={RequestMethod.GET, RequestMethod.POST})
    public void toMain(HttpServletRequest request, HttpServletResponse response) {
        try {
            VelocityContext velocityContext = new VelocityContext();
            String viewName = "system/back/login/work_new.html";
            ViewVelocity.view(request, response, viewName, velocityContext);
        } catch (Exception e) {
            logger.error("跳转到主页信息异常！！！");
            e.printStackTrace();
        }
    }

    /**
     * 工作台接口
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/main",method ={RequestMethod.GET, RequestMethod.POST})
    public AjaxJson main(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            LoginUser loginUser = getCurrentUser(request);
            if(loginUser == null) {
                j.setSuccess(false);
                j.setMsg("请登录后再做处理！");
                return j;
            }
            JwSystemUser u = userService.queryById(Long.valueOf(loginUser.getId()));
            StudyAdviser adviser = studyAdvService.findByUserNumber(u.getUserId());
            Map<String, Object> map = new HashMap<>();
            map.put("user", u);
            String date = DateUtil.dateToString(new Date());//当天日期
            String serverDate = DateUtil.getPastDate(7);//前七天日期
            String thirtyDate = DateUtil.getPastDate(30);//前30天日期
            Integer dayNum = posterManagerService.count(new PosterManager(date, adviser.getId()));//获取当日扫码数量
            Integer servenNum = posterManagerService.count(new PosterManager(serverDate, adviser.getId()));//获取近七日扫码数量
            Integer thirtyNum = posterManagerService.count(new PosterManager(thirtyDate, adviser.getId()));//获取近30天扫码数量
            String dayMoneyNum = courseOrderService.count(new CourseOrder(2, adviser.getId(), date)).toString();
            String serverMoneyNum = courseOrderService.count(new CourseOrder(2, adviser.getId(), serverDate)).toString();
            String thirtyMoneyNum = courseOrderService.count(new CourseOrder(2, adviser.getId(), thirtyDate)).toString();
            map.put("dayNum", dayNum);//日扫码
            map.put("sevenDayNum", servenNum);//七日扫码
            map.put("thirtyNum", thirtyNum);//三十日扫码
            map.put("dayMoneyNum", dayMoneyNum);//当日业绩
            map.put("serverMoneyNum", serverMoneyNum);//本周业绩
            map.put("thirtyMoneyNum", thirtyMoneyNum);//本月业绩

            Integer year = Integer.valueOf(DateUtil.dateToString(new Date(), "yyyy"));
            Date newYear = DateUtil.stringToDate((year + 1)+"-01-01","yyyy-MM-dd");
            int days = DateUtil.daysBetween(new Date(), newYear);
            map.put("days", days);//距离下一年还有多久
            map.put("nexYear", year + 1);
            j.setObj(map);
            j.setMsg("查询成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return j;
    }

    /**
     * 跳转到工作台
     * @param request
     * @param response
     */
    @RequestMapping(value = "/toPerson",method ={RequestMethod.GET, RequestMethod.POST})
    public void toPerson(HttpServletRequest request, HttpServletResponse response) {
        try {
            VelocityContext velocityContext = new VelocityContext();
            String viewName = "system/back/login/person.html";
            ViewVelocity.view(request, response, viewName, velocityContext);
        } catch (Exception e) {
            logger.error("跳转到主页信息异常！！！");
            e.printStackTrace();
        }
    }

    /**
     * 个人中心接口
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/person",method ={RequestMethod.GET, RequestMethod.POST})
    public AjaxJson person(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            LoginUser loginUser = getCurrentUser(request);
            if(loginUser == null) {
                j.setSuccess(false);
                j.setMsg("请登录后再做处理！");
                return j;
            }
            JwSystemUser u = userService.queryById(Long.valueOf(loginUser.getId()));
            Map<String, Object> map = new HashMap<>();
            map.put("user", u);
            map.put("wxStatus", "1");
            map.put("yhStatus", "1");
            j.setObj(map);
            j.setMsg("查询成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return j;
    }

    /**
     * 跳转到修改密码界面
     * @param request
     * @param response
     */
    @RequestMapping(value = "/toModifyPwd",method ={RequestMethod.GET, RequestMethod.POST})
    public void toModifyPwd(HttpServletRequest request, HttpServletResponse response) {
        try {
            VelocityContext velocityContext = new VelocityContext();
            String viewName = "system/back/login/modifyPwd.html";
            LoginUser u = getCurrentUser(request);
            velocityContext.put("username", u.getUserId());
            ViewVelocity.view(request, response, viewName, velocityContext);
        } catch (Exception e) {
            logger.error("跳转到主页信息异常！！！");
            e.printStackTrace();
        }
    }

    /**
     * 修改密码接口
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/modifyPwd",method ={RequestMethod.GET, RequestMethod.POST})
    public AjaxJson modifyPwd(HttpServletRequest request, String oldPassword, String password) {
        AjaxJson j = new AjaxJson();
        try {
            LoginUser loginUser = getCurrentUser(request);
            if(loginUser == null) {
                j.setSuccess(false);
                j.setMsg("请登录后再做处理！");
                return j;
            }
            JwSystemUser u = userService.queryById(Long.valueOf(loginUser.getId()));
            String passwordEncode = MD5Util.MD5Encode(oldPassword, "utf-8");//密码加密
            if(!passwordEncode.equals(u.getPassword())) {
                j.setSuccess(false);
                j.setMsg("旧密码不正确！");
                return j;
            }
            if(isAdmin(request)) {
                String newPassword = MD5Util.MD5Encode(password, "utf-8");//密码加密
                u.setPassword(newPassword);
                userService.updateUser(u);
            } else {
                StudyAdviser adviser = studyAdvService.findByUserNumber(u.getUserId());
                adviser.setPassword(password);
                studyAdvService.modifyPwd(adviser, u.getId());
            }
            j.setMsg("修改密码成功！");
        } catch (Exception e) {
            j.setMsg("修改密码异常！");
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }

}
